﻿using System;
using System.Globalization;
using System.Web.UI.WebControls;

namespace MyLib.Web.UI {
	/// <summary>
	/// 
	/// </summary>
	public class MyControlParameter : ControlParameter {
		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		/// <param name="control"></param>
		/// <returns></returns>
		protected override object Evaluate(System.Web.HttpContext context, System.Web.UI.Control control) {
			var value = base.Evaluate(context, control);

			TypeCode type;
			if (this.DbType != System.Data.DbType.Object)
				type = Parameter.ConvertDbTypeToTypeCode(DbType);
			else
				type = this.Type;

			if (type == TypeCode.DBNull) {
				return DBNull.Value;
			}
			if (value == null) {
				return null;
			}
			if ((type == TypeCode.Object) || (type == TypeCode.Empty)) {
				return value;
			}

			try {
				return Convert.ChangeType(value, type, CultureInfo.CurrentCulture);
			} catch (FormatException) {
				// Catch format exception.
				return null;
			}
		}
	} // end of MyControlParameter.
}
